<!-- 领料单设置 -->
<script setup lang="ts">
import type { VbenFormProps } from '#/adapter/form';
import type {
  OnActionClickParams,
  VxeGridListeners,
  VxeGridProps,
} from '#/adapter/vxe-table';
import type { Issue } from '#/api';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { VxeButton } from '@vben/plugins/vxe-table';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteIssue, getIssueTableList, issueheader } from '#/api';
import { mergeToolbarButtons, updateToolbarButtonStatus } from '#/utils';

import { confirm, messageError, messageSuccess } from '../common/common';
import { useColumns, useSearchSchema } from './data';
import IssueForm from './form.vue';

const btn = mergeToolbarButtons().value;
const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: IssueForm,
  destroyOnClose: true,
});

// 存储选中行的响应式变量
const selectedRows = ref<any[]>([]);

/**
 * 编辑
 * @param row
 */
function onEdit(row: Issue.Row) {
  row.attr1 = '2';
  formModalApi.setData(row).open();
}

/**
 * 查看
 * @param row
 */
function onView(row: Issue.Row) {
  row.attr1 = '1';
  formModalApi.setData(row).open();
}

/**
 * 创建
 */
function onAdd() {
  formModalApi.setData(null).open();
}
/**
 * 执行领出
 */
function onPiked(row: Issue.Row) {
  confirm(`确定执行出库吗？`, '提示').then(() => {
    issueheader(row.issueId.toString()).then(() => {
      messageSuccess(`执行成功`);
      refreshGrid();
    });
  });
}

/**
 * 删除
 * @param row
 */
function onDelete(row: Issue.Row | Issue.Row[]) {
  const ids = Array.isArray(row)
    ? row.map((item) => item.issueId)
    : [row.issueId];
  const idString = ids.join(',');
  confirm(`确定要删除生产领料单头编号为【${idString}】的数据吗？`, '提示').then(
    () => {
      deleteIssue(idString)
        .then(() => {
          messageSuccess(`删除成功`);
          refreshGrid();
        })
        .catch((error) => {
          messageError(error);
        });
    },
  );
}

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  wrapperClass: 'grid-cols-4',
  schema: useSearchSchema(),

  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  submitButtonOptions: {
    content: '搜索',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

const gridOptions: VxeGridProps<Issue.Row> = {
  columns: useColumns(onView, onActionClick),
  checkboxConfig: {
    highlight: true,
  },
  // 虚拟滚动配置项
  virtualYConfig: { enabled: true },
  keepSource: true,
  pagerConfig: {
    enabled: true,
    layouts: [
      'Total',
      'Sizes',
      'PrevJump',
      'PrevPage',
      'Number',
      'NextPage',
      'NextJump',
      'FullJump',
    ],
    align: 'right',
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const res = await getIssueTableList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
        return { items: res.rows, total: res.total };
      },
    },
  },
  tooltipConfig: {
    // 是否开启全局文本提示
    showAll: false,
  },
  toolbarConfig: {
    // 是否显示搜索表单控制按钮
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
    custom: true,
    zoom: true,
    refresh: { code: 'query' },
    buttons: btn,
    // buttons: mergeToolbarButtons([{ name: '测试', code: 'add', status: 'primary', icon: 'vxe-icon-add' }]).value
  },
};

const gridEvents: VxeGridListeners = {
  toolbarButtonClick({ code }) {
    switch (code) {
      case 'add': {
        onAdd();
        break;
      }
      case 'edit': {
        if (selectedRows.value.length === 1) {
          onEdit(selectedRows.value[0] as any);
        } else {
          confirm('请选择单行', '提示');
        }
        break;
      }
      case 'myDelete': {
        if (selectedRows.value.length > 0) {
          onDelete(selectedRows.value);
        }
        break;
      }
      default: {
        break;
      }
    }
    updateToolbarButtonStatus(selectedRows, btn); // 更新按钮状态
  },
  checkboxChange() {
    selectedRows.value = gridApi?.grid?.getCheckboxRecords();
    updateToolbarButtonStatus(selectedRows, btn); // 更新按钮状态
  },
  checkboxAll() {
    selectedRows.value = gridApi?.grid?.getCheckboxRecords();
    updateToolbarButtonStatus(selectedRows, btn); // 更新按钮状态
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});

/**
 * 处理表格操作列点击事件的函数
 *
 * @param {OnActionClickParams<Issue.Row>} - 包含操作代码和行数据的对象
 */
function onActionClick({ code, row }: OnActionClickParams<Issue.Row>) {
  switch (code) {
    case 'edit': {
      onEdit(row);
      break;
    }
    case 'myDelete': {
      onDelete(row);
      break;
    }
    case 'onPiked': {
      onPiked(row);
      break;
    }
    case 'onView': {
      onView(row);
      break;
    }
    default: {
      break;
    }
  }
  updateToolbarButtonStatus(selectedRows); // 更新按钮状态
}

/**
 * 刷新表格
 */
function refreshGrid() {
  gridApi.query();
}
</script>

<template>
  <div class="vp-raw w-full">
    <FormModal @success="refreshGrid" />
    <Grid>
      <template #action="{ row }">
        <div v-if="row.status === 'PREPARE'">
          <VxeButton
            mode="text"
            icon="vxe-icon-signature"
            @click="onActionClick({ code: 'edit', row })"
            status="primary"
          >
            编辑
          </VxeButton>
          <VxeButton
            icon="vxe-icon-delete"
            mode="text"
            @click="onActionClick({ code: 'myDelete', row })"
            status="error"
          >
            删除
          </VxeButton>
        </div>
        <div v-else-if="row.status === 'APPROVED'">
          <VxeButton
            mode="text"
            icon="vxe-icon-radio-checked"
            @click="onActionClick({ code: 'onPiked', row })"
            status="primary"
          >
            执行领出
          </VxeButton>
        </div>
        <div v-else-if="row.status === 'APPROVING'">
          <VxeButton
            mode="text"
            icon="vxe-icon-click-button"
            @click="onActionClick({ code: 'onPiking', row })"
            status="primary"
          >
            执行拣货
          </VxeButton>
        </div>
      </template>
    </Grid>
  </div>
</template>

<style scoped>
.blue-text {
  color: #1890ff;
}
</style>
